package com.kws.merchant.service.impl;


import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.kws.common.security.auth.AuthUtil;
import com.kws.merchant.domain.ContractSignature;
import com.kws.merchant.domain.OperationPolling;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kws.merchant.domain.OperationPollingDevice;
import com.kws.merchant.domain.OperationWorkOrder;
import com.kws.merchant.domain.po.DisposePollingPo;
import com.kws.merchant.domain.po.OperationPollingPo;
import com.kws.merchant.domain.po.PollingPo;
import com.kws.merchant.mapper.OperationPollingMapper;
import com.kws.merchant.service.OperationPollingDeviceService;
import com.kws.merchant.service.OperationPollingService;
import com.kws.merchant.util.TimeUtil;
import com.kws.system.api.domain.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 运维-巡检管理(OperationPolling)表服务实现类
 *
 * @author yxy
 * @since 2024-10-28 11:32:39
 */
@Service("operationPollingService")
public class OperationPollingServiceImpl extends ServiceImpl<OperationPollingMapper, OperationPolling> implements OperationPollingService {

    @Resource
    private OperationPollingMapper operationPollingMapper;
    @Autowired
    private OperationPollingDeviceService operationPollingDeviceService;


    /**
     * 分页查询列表
     */
    @Override
    public Page<OperationPolling> pageList(PollingPo pollingPo) {
        Integer pageSize = pollingPo.getPageSize();
        Integer totalPage = pollingPo.getTotalPage();
        String itemName = pollingPo.getItemName();
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        String sql=" o.merchant_id="+sysUser.getCompanyId();
        if (StringUtils.isNotEmpty(itemName)){
            sql+=" and i.item_name like '%"+itemName+"%' ";
        }
        int sizeNum = (pageSize - 1) * totalPage;//计算分页
        int total = operationPollingMapper.countToTal(sql);
        //查询签名数据
        List<OperationPolling> records=operationPollingMapper.getRecords(sql,sizeNum,totalPage);

        Page<OperationPolling> page = new Page<>();
        page.setRecords(records);
        page.setTotal(total);
        page.setCurrent(pageSize);
        page.setPages((total+totalPage-1)/totalPage);
        page.setSize(totalPage);
        return page;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object delete(List<Long> idList) {
        idList.forEach(X->{
            //根据巡检id删除巡检设备
            operationPollingDeviceService.deleteByPollingId(X);
            this.removeById(X);
        });
        return true;
    }

    /**
     * 查看
     * @param id
     * @return
     */
    @Override
    public OperationPolling detailById(Long id) {
        OperationPolling operationPolling = operationPollingMapper.detailById(id);
        if (ObjectUtils.isEmpty(operationPolling)){
            throw new RuntimeException("没有该巡检信息");
        }
        //根据巡检id查询巡检设备
        List<OperationPollingDevice> pollingDevices=operationPollingDeviceService.listByPollingId(operationPolling.getId());
        operationPolling.setPollingDevices(pollingDevices);
        return operationPolling;
    }

    /**
     * 新增巡检数据
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object addPolling(OperationPollingPo operationPollingPo) {
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        OperationPolling operationPolling = new OperationPolling();
        operationPolling.setMerchantId(sysUser.getCompanyId());
        operationPolling.setPollingNo("XJ"+ UUID.randomUUID());//巡检编号
        operationPolling.setStatus(1);//状态
        operationPolling.setItemId(operationPollingPo.getItemId());
        operationPolling.setPeriod(operationPollingPo.getPeriod());
        operationPolling.setSite(operationPollingPo.getSite());
        operationPolling.setPollingUserId(operationPollingPo.getPollingUserId());
        this.save(operationPolling);
        List<Long> deviceIds = operationPollingPo.getDeviceIds();
        ArrayList<OperationPollingDevice> list = new ArrayList<>();
        deviceIds.forEach(x->{
            OperationPollingDevice pollingDevice = new OperationPollingDevice();
            pollingDevice.setPollingId(operationPolling.getId());
            pollingDevice.setItemId(operationPollingPo.getItemId());
            pollingDevice.setDeviceId(x);
            pollingDevice.setStatus(0);//新增巡检设备默认正常
            list.add(pollingDevice);
        });
        //添加巡检设备
        operationPollingDeviceService.saveBatch(list);
        return true;
    }

    /**
     * 处理巡检
     * @param disposePollingPo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object disposePolling(DisposePollingPo disposePollingPo) {
        OperationPolling operationPolling = this.getById(disposePollingPo.getPollingId());
        if (ObjectUtils.isEmpty(operationPolling)){
            throw new RuntimeException("没有该巡检信息");
        }
        //修改设备数据状态
        List<OperationPollingDevice> pollingDevices = disposePollingPo.getPollingDevices();
        //修改巡检记录
        operationPollingDeviceService.updatePollingDevice(pollingDevices);
        //加入下次巡检时间，当前时间+周期时间
        Integer period = operationPolling.getPeriod();
        Date addDay = TimeUtil.addDayByDate(period);
        operationPolling.setNextPollingTime(addDay);
        operationPolling.setNextPollingUser(operationPolling.getPollingUserId());
        operationPolling.setPollingResult(disposePollingPo.getPollingResult());
        //巡检状态
        operationPolling.setStatus(0);
        return this.updateById(operationPolling);
    }

    /**
     * 通过状态查询巡检
     * @param status
     * @return
     */
    @Override
    public List<OperationPolling> listByStatus(int status) {
        return this.list(Wrappers.<OperationPolling>lambdaQuery().eq(OperationPolling::getStatus,status));
    }

    /**
     * 查询商家所有巡检
     * @param companyId
     * @return
     */
    @Override
    public List<OperationPolling> listByMerchant(Long companyId) {
        return this.list(Wrappers.<OperationPolling>lambdaQuery().eq(OperationPolling::getMerchantId,companyId));
    }

    @Override
    public Double countWorkTypeBySql(Long companyId, String sql) {
        return operationPollingMapper.countWorkTypeBySql(companyId,sql);
    }

}
